import serial
"""
目前，此代码已经可以接收解析来自调试助手的数据
trs函数出现问题
"""

# todo 找可用串口


def init(portx1):
    # todo 这个函数可能要拆开
    portx = portx1
    bps = 115200
    timex = 5
    ser = serial.Serial(portx, bps, timeout=timex)
    return ser


def trsB(a):
    # """
    # b\x  ->  0x
    # :param a: bytes \x
    # :return: 字符串 0x
    # """
    ret = ""
    for i in a:
        temp = hex(i)
        if len(temp) == 3:
            temp = "0x0" + temp[2]
        ret += temp
    return ret


def check_ver(frame1):
    datas = frame1[8:-12]
    # unpack:
    datas = eval("0x" + datas.replace("0x", ""))
    command = eval(frame1[-12:-8])
    cal_ver = hex(datas + command)[-2:]
    rel_ver = frame1[-6:-4]
    if cal_ver != rel_ver:
        return 1
    return 0


def fun_inttest(data):
    data = eval("0x" + data.replace("0x", ""))
    print("haha,got it", data)


def ana_command(frame1):
    funDict = {
        "0x99": fun_inttest,
    }
    func = funDict.get(frame1[-12:-8], None)
    if func:
        func(frame1[8:-12])
    else:
        print("这个指令找不到匹配的")


ser = init("COM7")
print("program start +w+")
while True:
    # todo 设置终止
    get = ser.read()
    if get == b"\xFE":
        frame1 = "0xFE"
        temp = trsB(ser.read())
        frame1 += temp
        for i in range(eval(temp) + 1):
            # todo 此处有性能损失待优化
            frame1 += trsB(ser.read())
        if ser.read() == b"\xFF":
            frame1 += "0xFF"
            if check_ver(frame1) == 1:
                break
            # todo 暂时这里没有考虑返回请求重发的情况
            ana_command(frame1)
